package com.inossem.utils.request;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruImageCache implements ImageCache {

    private static LruCache<String, Bitmap> mMemoryCache;

    private static LruImageCache lruImageCache;

    /**
     * 构造方法
     * @return 返回LruImageCache对象
     */
    private LruImageCache() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    /**
     * 获取LruImageCache对象
     */
    public static synchronized LruImageCache instance() {
        if (lruImageCache == null) {
            lruImageCache = new LruImageCache();
        }
        return lruImageCache;
    }

    @Override
    /**
     * 获取图片bitmap对象
     * @param key 键
     * @return 返回bitmap对象
     */
    public Bitmap getBitmap(String key) {
        return mMemoryCache.get(key);
    }

    @Override
    /**
     * 将图片放入缓存中
     * @param key 键
     * @param bitmap 图片的bitmap对象
     */
    public void putBitmap(String key, Bitmap bitmap) {
        if (getBitmap(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

}
